/*
 * datetime.cpp
 *
 *  Created on: 2011-3-21
 *      Author: minorityee
 */

#include "datetime/datetime.h"
#include "common/common_def.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

// pattern: yyyy-mm-dd hh:mm:ss
CDateTime::CDateTime(const char* cszDateTime)
{
	struct tm t;
	char szDateTime[MAX_DATETIME_LEN + 1] = {0};
	strncpy(szDateTime, cszDateTime, sizeof(szDateTime));
	char *p = szDateTime;
	p[4] = '\0'; // yyyy
	t.tm_year = atoi(p) - 1900;
	p += 4 + 1;
	p[2] = '\0'; // mm
	t.tm_mon = atoi(p) - 1;
	p += 2 + 1;
	p[2] = '\0'; // dd
	t.tm_mday = atoi(p);
	p += 2 + 1;
	p[2] = '\0'; // hh
	t.tm_hour = atoi(p);
	p += 2 + 1;
	p[2] = '\0'; // mm
	t.tm_min = atoi(p);
	p += 2 + 1;
	p[2] = '\0'; //ss
	t.tm_sec = atoi(p);
#ifndef WIN32
	nUTime_ = mktime(&t);
#endif
	nUTime_ *= US_PER_SECOND;
}

int32_t CDateTime::ToString(char *szDateTime, unsigned& strlen) const
{
	if(MAX_DATETIME_LEN + 1 > strlen)
		return E_INVALIDARG;
	time_t rawtime = nUTime_ / US_PER_SECOND;
	struct tm datetime = { 0 };
#ifndef WIN32
	localtime_r(&rawtime, &datetime);
#else
	struct tm* pTm = NULL;
	pTm = localtime(&rawtime);
	memcpy(&datetime, pTm, sizeof(datetime));
#endif
	char *p = szDateTime;
	// yyyy-
	snprintf(p, 4 + 1, "%04d", datetime.tm_year + 1900);
	p += 4;
	*p++ = '-';
	// mm-
	snprintf(p, 2 + 1, "%02d", datetime.tm_mon + 1);
	p += 2;
	*p++ = '-';
	// dd
	snprintf(p, 2 + 1, "%02d", datetime.tm_mday);
	p += 2;
	*p++ = ' ';
	// hh:
	snprintf(p, 2 + 1, "%02d", datetime.tm_hour);
	p += 2;
	*p++ = ':';
	// mm:
	snprintf(p, 2 + 1, "%02d", datetime.tm_min);
	p += 2;
	*p++ = ':';
	// ss
	snprintf(p, 2 + 1, "%02d", datetime.tm_sec);
	p[2] = '\0';
	strlen = MAX_DATETIME_LEN;
	return S_OK;
}

CDateTime::~CDateTime()
{

}
